﻿using DeviceCommons.DataHandling;
using DeviceCommons.DeviceMessages.Abstractions;
using DeviceCommons.DeviceMessages.Models.V1;

namespace DeviceCommons.DeviceMessages.Serialization.V2.Parsers
{
    public class DeviceMessageInfoParser : AbstractMessageParser<IDeviceMessageInfo>, IDeviceMessageInfoParser, IContextAwareParser
    {
        private ParsingContext? _context;

        public DeviceMessageInfoParser() : base(new DeviceMessageInfo())
        {

        }

        public override IDeviceMessageInfo Parser(ReadOnlySpan<byte> bytes)
        {
            int currentIndex = 1;
            IDeviceMessageInfo model = new DeviceMessageInfo();
            model.DIDBytes = bytes.Slice(currentIndex, bytes[0]).ToArray();
            currentIndex += bytes[0];
            model.DeviceType = bytes.Slice(currentIndex, 1)[0];
            currentIndex++;
            
            // 使用现有上下文或创建新上下文
            var context = _context ?? ParsingContext.Create(model.DeviceType);
            
            // 确保上下文包含正确的设备类型
            if (context.CurrentDeviceType == null)
            {
                context.CurrentDeviceType = model.DeviceType;
            }
            
            // 将上下文传递给子解析器
            if (DeviceMessageSerializerProvider.InfoReadingsV2Par is IContextAwareParser contextAwareParser)
            {
                contextAwareParser.SetContext(context);
            }
            
            model.Reading = DeviceMessageSerializerProvider.InfoReadingsV2Par.Parser(bytes[currentIndex..]);
            Model = model;
            return model;
        }

        public void SetContext(ParsingContext context)
        {
            _context = context;
        }

        public ParsingContext? GetContext()
        {
            return _context;
        }
    }
}
